package x.ovo.wechat.bot.login;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import x.ovo.wechat.bot.common.Constant;
import x.ovo.wechat.bot.common.http.session.LoginSession;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 热重载
 *
 * @author ovo, created by 2024/05/03
 */
@Data
@Slf4j
public class HotReload implements Serializable {

    private LoginSession session;
    private Map<String, List<Cookie>> cookieStore = MapUtil.newHashMap();

    public static HotReload build(LoginSession session, Map<String, List<Cookie>> cookieStore) {
        HotReload hotReload = new HotReload();
        hotReload.setSession(session);
        hotReload.cookieStore = cookieStore;
        return hotReload;
    }

    public String toJson() {
        JSONObject object = JSONUtil.createObj().set("session", this.session);

        List<JSONObject> cookies = cookieStore.entrySet().stream()
                .map(entry -> {
                    List<String> list = entry.getValue().stream()
                            .map(Cookie::toString)
                            .toList();
                    return JSONUtil.createObj().set(entry.getKey(), list);
                }).toList();
        object.set("cookies", cookies);
        return JSONUtil.toJsonPrettyStr(object);
    }

    public void save() {
        if (this.session.getLastExitTime() == 0) {
            this.session.setLastExitTime(System.currentTimeMillis() / 1000);
        }
        FileUtil.writeBytes(this.toJson().getBytes(), Constant.LOGIN_FILE);
        log.info("自动登录信息写入完成");
    }

    /**
     * 重新登录
     */
    public void reLogin() {
        JSONObject object = JSONUtil.readJSONObject(Constant.LOGIN_FILE, StandardCharsets.UTF_8);
        this.session = object.getBean("session", LoginSession.class);
        List<JSONObject> cookies = object.getJSONArray("cookies").stream()
                .map(JSONUtil::parseObj)
                .toList();
        cookies.forEach(cookieJson -> cookieJson.keySet().forEach(host -> {
            HttpUrl url = new HttpUrl.Builder().scheme("https").host(host).build();
            List<Cookie> list = cookieJson.getJSONArray(host).stream().map(String::valueOf).map(s -> Cookie.parse(url, s)).toList();

//            Map<String, Cookie> map = cookieJson.getJSONArray(host).stream()
//                    .map(String::valueOf)
//                    .map(s -> Cookie.parse(url, s))
//                    .collect(Collectors.toMap(Cookie::name, cookie -> cookie));

            this.cookieStore.put(host, list);
//            list.forEach(cookie -> {
//                if (cookie.name().startsWith("webwx_auth_ticket")) this.session.setAuthTicket(cookie.value());
//                if (cookie.name().startsWith("webwx_data_ticket")) this.session.setDataTicket(cookie.value());
//            });
        }));
    }

}
